//
//  MYGSelectUserController.swift
//  MYGrow
//
//  Created by 林矗 on 2024/4/14.
//

import UIKit
import MJRefresh

class MYGSpeakerSearchVC: MYGBaseController {
    
    var meeting_id:String = ""
    private var page = 1
    private var searchStr = ""
    private var expertArra:[MYGAcademicExpertListModel] = []

    // MARK: - Property
    var indexArray = [String]()
    var sortedNameDict = [String:[MYGAcademicExpertListModel]]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configUI()
    }
    
    // MARK: - UI
    private func configUI() {
        title = "讲者检索"
        view.addSubview(serachBView)
        serachBView.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(23)
            make.left.equalToSuperview().offset(16)
            make.height.equalTo(35)
        }
        
        serachBView.addSubview(searchTextField)
        searchTextField.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(11)
            make.right.equalToSuperview().offset(-11)
            make.top.bottom.equalToSuperview()
        }
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(serachBView.snp.bottom).offset(10)
            make.left.right.bottom.equalToSuperview()
        }
        
        getExportList()
    }
    

    // 专家
    private func getExportList(){
        var params :[String:Any] = [:]
        params["meeting_id"] = meeting_id
        params["type"] = "3"
        params["key"] = searchStr
        params["page"] = page
        params["pageSize"] = 20
        
        MYGLoading.show()
        MMYGNetwork<MYGHomePageAPI, MYGPageModel<MYGAcademicExpertListModel>>.request(target: .foreign(param: params)) { [self] result in
            MYGLoading.hide()
            guard let item = result else {
                return
            }
            self.tableView.mj_header?.endRefreshing()
            if item.page.page <= 1 {
                self.expertArra = item.list
            } else {
                self.expertArra.append(contentsOf: item.list)
            }
            
            if item.page.total <= self.expertArra.count {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.endRefreshing()
            }
            
            configDataSource()
            
        } failed: { _, error in
            self.tableView.mj_header?.endRefreshing()
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
        
        }
    
    
    func configDataSource() {
        self.indexArray.removeAll()
        self.sortedNameDict.removeAll()
        for(_,obj) in self.expertArra.enumerated() {
            self.indexArray.append(obj.expertCn.getFirstLetter())
        }
        self.indexArray = self.indexArray.uniqued{$0}
        for (_,obj) in self.indexArray.enumerated() {
            var dataArray = [MYGAcademicExpertListModel]()
            for(_,data) in self.expertArra.enumerated() {
                if data.expertCn.getFirstLetter() == obj {
                    dataArray.append(data)
                }
            }
            self.sortedNameDict[obj] = dataArray
        }
        self.indexArray = self.indexArray.sorted()
        self.tableView.reloadData()
    }
    // MARK: - lazy load
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.separatorStyle = .none
        tableView.showsVerticalScrollIndicator = false
        tableView.showsHorizontalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = 70
        tableView.register(cellWithClass: MYGExpertTableViewCell.self)
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.indexArray.removeAll()
            self?.sortedNameDict.removeAll()
            self?.page = 1
            self?.getExportList()
        })
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getExportList()
        })
       
        return tableView
    }()
    
    lazy var searchTextField: UITextField = {
        let control = UITextField()
        control.textAlignment = .center
        control.placeholder = "请输入标题或讲者搜索"
        control.delegate = self
        control.clearButtonMode = .whileEditing
        control.returnKeyType = .search
        return control
    }()
    
    var serachBView: UIView = {
        let control = UIView()
        control.backgroundColor = UIColor.init(hexString: "#F5F5F5")
        control.addCorner(radius: 17.5)
        return control
    }()
    
}

extension MYGSpeakerSearchVC: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGExpertTableViewCell.self)
        if let model = self.sortedNameDict[self.indexArray[indexPath.section]]?[indexPath.row] {
            cell.model = model
        }
        return cell
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.sortedNameDict.keys.count
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.sortedNameDict[self.indexArray[section]]?.count ?? 0
    }
    
      func sectionIndexTitles(for tableView: UITableView) -> [String]? {
          return indexArray
      }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return self.indexArray[section]
    }

    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let model = self.sortedNameDict[self.indexArray[indexPath.section]]?[indexPath.row] {
            let vc = MYGExpertTaskDetailViewController()
            vc.id = model.id
            self.navigationController?.pushViewController(vc)
        }
    }
}
extension MYGSpeakerSearchVC: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        if textField.text?.count ?? 0 > 0 {
            searchStr = textField.text!
        }else{
            searchStr = ""
        }
        self.page = 1
        getExportList()
        return true
    }
}
